
/*
 * @Author: WLang
 * @LastEditors: WLang
 * @Description: 
 * @Date: 2023-06-29 13:50:20
 * @LastEditTime: 2023-07-19 17:11:20
 * @FilePath: \myblog\src\store\index.js
 */
import Vue from 'vue'
import Vuex from 'vuex'
import modal from './modules/modal'
import like from './modules/like'
import base from '@/config/base.config'
import store from 'store'
import http from '@/api/http'
import {isMobile} from '@/core/isMobile'
import router from '../router'
const { io } = require("socket.io-client");
const { TOKEN_NAME } = base
let selfWill = true
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    token: store.get(TOKEN_NAME) || "",
    userInfo: {},
    live2Ddis: false
  },
  getters: {
    userInfo(state) {
      if (state.token) {
        return state.userInfo
      }
    }
  },
  mutations: {
    RIGHT_LIVE2D_SET(state) {
      state.live2Ddis = true
    },
    LEFT_LIVE2D_SET(state) {
      state.live2Ddis = false
    },
    CANCEL_TOKEN(state) {
      state.token = '';
      store.remove(TOKEN_NAME);
    },
    SET_TOKEN(state) {
      state.token = store.get(TOKEN_NAME)
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async login({ dispatch, commit }) {
      commit('SET_TOKEN')
      dispatch('getUserInfo')
    },
    //登出
    async logout({ dispatch, commit, getters }) {
      if (!isMobile())
      {
        selfWill = true
        Vue.prototype.$ws.close()
      }
      commit('CANCEL_TOKEN')
    },
    async online({ commit, getters }) {
      //单点登录
      Vue.prototype.$ws = io(process.env.VUE_APP_USER_CHAT_PATH, {transports: ['websocket']})
      let {nikname, _id} = getters.userInfo
      Vue.prototype.$ws.emit('online', {uid:_id, nikname})
      Vue.prototype.$ws.on('disconnect', () => {
        Vue.prototype.$ws = null
        let message = '账号已在其他设备登录'
      //如果是被重复登录顶掉强制下线
      if(selfWill)
      {
        message = `再见 ${nikname}`
      }
        Vue.prototype.$message({
          title: '退出登录',
          message: message,
          type: 'warning'
        });
        selfWill = false
        commit('CANCEL_TOKEN')
        if (!isMobile()) {
          if(router.app._route.name !== 'index')
        {
          router.push('/index')
        }
        }
      })
    },
    async getUserInfo({ commit, dispatch }) {
      try {
        let userInfo = await http({ type: 'getUserInfo' })
        commit('SET_USERINFO', userInfo)
        if (!isMobile())
        {
          Vue.prototype.$message({
            title: '登录成功',
            message: `欢迎登录 ${userInfo.nikname}`,
            type: 'success'
          });
          if(router.app._route.name !== 'index')
          {
            router.push('/index')
          }
          dispatch('online')
        }
      }
      catch (err) {
        console.log(err)
      }
    }
  },
  modules: {
    modal,
    like
  }
})
